import _ from 'lodash'

export default (() => {
  /**
   * 检查给定路由是否有权限访问
   *
   * @param {Object} route -检测路由
   * @param {Array} permissions -权限数组
   */
  function hasPermission (route, permissions) {
    if (!route.meta) {
      return true
    }
    if (!route.meta.permission || route.meta.hideInMenu) {
      return true
    }
    return hasOneOf(permissions, route.meta.permission)
  }

  /**
   * x包含y的某一项
   *
   * @param {Array} x
   * @param {Array} y
   */
  function hasOneOf (x, y) {
    if (!x || !y) return false
    // x = toArray(_.cloneDeep(x))
    // y = toArray(_.cloneDeep(y))
    // return x.some(z => y.indexOf(z) > -1)
    return x.indexOf(y) > -1
  }

  /**
   * 对象是否有有效子节点
   *
   * @param {Object} obj
   * @returns {Boolean}
   */
  function hasChild (obj) {
    return obj.children && obj.children.length > 0
  }

  /**
   * 过滤用户可访问路由
   *
   * @param {Array}   routes - 待检查权限路由
   * @param {Array}   userAuthorities - 用户权限数据
   * @param {Boolean} debug - 调试模式
   * @returns {Array} 用户有权限路由
   */
  function filter (routes, userAuthorities, debug) {
    if (debug) return routes
    function _filter (routes) {
      return routes.filter((item) => {
        if (hasChild(item)) {
          item.children = _filter(item.children)
        }
        return hasPermission(item, userAuthorities)
      })
    }

    return _filter(_.cloneDeep(routes))
  }

  /**
   * 检测是否可进入给定路由
   *
   * @param {Object} to - 路由对象
   * @param {Array} routes - 全部路由
   * @param {Array} userPermissions - 用户权限
   * @returns {Boolean}
   */
  function canJump (to, routes, userPermissions) {
    function check (list) {
      return list.some(route => {
        if (route.name === to.name) {
          return hasPermission(route, userPermissions)
        } else if (route.children && route.children.length) {
          return check(route.children)
        }
      })
    }
    return check(routes)
  }

  return {
    filter,
    canJump
  }
})()
